#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindowClass)
{
    ui->setupUi(this);
    settings = new QSettings("Roger Grayson", "rrenamer32");

    _threads = QThread::idealThreadCount();
    if(_threads == -1)
    {   _threads = 1;
    }
    _activeThreads = 0;
}

MainWindow::~MainWindow()
{
    delete ui;
    delete settings;
}

void MainWindow::on_action_Open_Directory_activated()
{
    dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"), ".",
                                            QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    if(dir==NULL)
           return;

    QDir directory(dir);
    ui->groupBox->setTitle(dir);

    ui->plainTextEdit->clear();
    filesOrig.clear();
    filesNew.clear();

    _dirFilter = QDir::Files | QDir::NoDotAndDotDot;
    directory.setFilter(_dirFilter);
    filesOrig = directory.entryList();

    for(int i=0; i<filesOrig.count(); i++)
    {   ui->plainTextEdit->appendPlainText(filesOrig.at(i));
    }
    QString qsTemp = QString("Loaded %1 files").arg(filesOrig.count());
    ui->statusBar->showMessage(qsTemp);
}

void MainWindow::on_action_RRename_activated()
{
    filesNew.clear();
    filesNew = ui->plainTextEdit->toPlainText().split("\n");
    if(filesNew.count() != filesOrig.count())
    {   QMessageBox::critical(this, "ERROR","Number of output files != number of input files",QMessageBox::Ok);
        return;
    }

    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this,"Confirmation","Are you sure you want to rename all files?",
                                  QMessageBox::Yes | QMessageBox::No);
    if(reply == QMessageBox::No)
        return;

    int perThread = filesNew.count()/_threads;
    int extras = filesNew.count()%_threads;
    _threadErrors=0;

    renameThreads = new Rename[_threads];

    int offset=0;
    int extra;
    int ops;

    for(int i=0; i<_threads; i++)
    {
        ops = perThread;
        if(extras)
        {   extras--;extra=1;ops+=extra;
        }
        connect(&(renameThreads[i]),SIGNAL(finished()),
                this,SLOT(renameThreadFinished()), Qt::QueuedConnection);

        renameThreads[i].run(dir, filesOrig, filesNew, offset, ops);
        _activeThreads++;
        offset+=ops;
    }

    //filesOrig.clear(); //may not be necessary, and may slow down large rename operations?
    //filesOrig = filesNew;
}

void MainWindow::renameThreadFinished()
{
    if( --_activeThreads == 0)
    {   QString qsTemp("Renaming complete.");
        QMessageBox::information(this,"Finished Renameing",qsTemp,QMessageBox::Ok);
    }
}

void MainWindow::on_action_About_activated()
{
    About about(this);
    about.exec();
}
